package com.xy.xyaicpzs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xy.xyaicpzs.common.requset.PredictRecordQueryRequest;
import com.xy.xyaicpzs.common.response.PageResponse;
import com.xy.xyaicpzs.domain.entity.LotteryDraws;
import com.xy.xyaicpzs.domain.entity.PredictRecord;
import com.xy.xyaicpzs.domain.vo.UserPredictStatVO;
import com.xy.xyaicpzs.mapper.LotteryDrawsMapper;
import com.xy.xyaicpzs.mapper.PredictRecordMapper;
import com.xy.xyaicpzs.service.DataAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 数据分析服务实现类
 */
@Service
public class DataAnalysisServiceImpl implements DataAnalysisService {
    
    @Autowired
    private PredictRecordMapper predictRecordMapper;
    
    @Autowired
    private LotteryDrawsMapper lotteryDrawsMapper;
    
    @Override
    public UserPredictStatVO getUserPredictStat(Long userId) {
        UserPredictStatVO statVO = new UserPredictStatVO();
        
        // 查询用户的所有预测记录
        QueryWrapper<PredictRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                   .eq("type", "ssq");
        List<PredictRecord> predictRecords = predictRecordMapper.selectList(queryWrapper);
        
        if (predictRecords == null || predictRecords.isEmpty()) {
            statVO.setUserId(userId);
            statVO.setPredictCount(0L);
            statVO.setHitCount(0L);
            statVO.setPendingCount(0L);
            statVO.setDrawnCount(0L);
            statVO.setHitRate(java.math.BigDecimal.ZERO);
            return statVO;
        }
        
        // 统计数据
        long totalPredicts = predictRecords.size();
        long hitCount = 0L;
        long pendingCount = 0L;
        long drawnCount = 0L;
        
        for (PredictRecord record : predictRecords) {
            if ("待开奖".equals(record.getPredictStatus())) {
                pendingCount++;
            } else if ("已中奖".equals(record.getPredictStatus())) {
                hitCount++;
                drawnCount++;
            } else if ("未中奖".equals(record.getPredictStatus())) {
                drawnCount++;
            }
        }
        
        // 计算命中率
        java.math.BigDecimal hitRate = drawnCount > 0 ? 
            java.math.BigDecimal.valueOf(hitCount).divide(java.math.BigDecimal.valueOf(drawnCount), 4, java.math.RoundingMode.HALF_UP) : 
            java.math.BigDecimal.ZERO;
        
        statVO.setUserId(userId);
        statVO.setPredictCount(totalPredicts);
        statVO.setHitCount(hitCount);
        statVO.setPendingCount(pendingCount);
        statVO.setDrawnCount(drawnCount);
        statVO.setHitRate(hitRate);
        
        return statVO;
    }
    
    @Override
    public int processPendingPredictions() {
        // 查询所有待开奖的预测记录
        QueryWrapper<PredictRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("predictStatus", "待开奖")
                   .eq("type", "ssq");
        List<PredictRecord> pendingRecords = predictRecordMapper.selectList(queryWrapper);
        
        int processedCount = 0;
        
        for (PredictRecord record : pendingRecords) {
            // 查询对应期号的开奖结果
            LotteryDraws draws = lotteryDrawsMapper.selectById(record.getDrawId());
            if (draws != null) {
                // 比较预测号码与开奖号码，计算中奖结果
                String result = calculatePredictResult(record, draws);
                long bonus = calculateBonus(result);
                if(result.equals("未中奖")){
                    record.setPredictStatus("未中奖");
                }else{
                    record.setPredictStatus("已中奖");
                }
                
                // 更新预测记录

                record.setPredictResult(result);
                record.setBonus(bonus);
                predictRecordMapper.updateById(record);
                
                processedCount++;
            }
        }
        
        return processedCount;
    }
    
    @Override
    public PageResponse<PredictRecord> queryPredictRecords(PredictRecordQueryRequest request) {
        // 构建查询条件
        QueryWrapper<PredictRecord> queryWrapper = new QueryWrapper<>();
        
        // 添加用户ID筛选条件
        if (request.getUserId() != null) {
            queryWrapper.eq("userId", request.getUserId());
        }
        
        // 添加预测状态筛选条件
        if (StringUtils.hasText(request.getPredictStatus())) {
            queryWrapper.eq("predictStatus", request.getPredictStatus());
        }
        
        // 添加类型筛选条件，只查询双色球类型
        queryWrapper.eq("type", "ssq");
        
        // 按预测时间降序排序
        queryWrapper.orderByDesc("predictTime");
        
        // 执行分页查询
        Page<PredictRecord> page = new Page<>(request.getCurrent(), request.getPageSize());
        Page<PredictRecord> resultPage = predictRecordMapper.selectPage(page, queryWrapper);
        
        // 构建分页响应对象
        return PageResponse.of(
                resultPage.getRecords(), 
                resultPage.getTotal(), 
                (int) resultPage.getCurrent(), 
                (int) resultPage.getSize()
        );
    }
    
    @Override
    public long getTotalPredictCount() {
        // 获取全部预测记录数量（只统计双色球类型）
        QueryWrapper<PredictRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "ssq");
        return predictRecordMapper.selectCount(queryWrapper);
    }
    
    /**
     * 计算预测结果
     */
    private String calculatePredictResult(PredictRecord record, LotteryDraws draws) {
        // 比较红球
        int redMatches = 0;
        Integer[] predictReds = {record.getRedBall1(), record.getRedBall2(), record.getRedBall3(), 
                                record.getRedBall4(), record.getRedBall5(), record.getRedBall6()};
        Integer[] drawReds = {draws.getRedBall1(), draws.getRedBall2(), draws.getRedBall3(), 
                             draws.getRedBall4(), draws.getRedBall5(), draws.getRedBall6()};
        
        for (Integer predictRed : predictReds) {
            for (Integer drawRed : drawReds) {
                if (predictRed != null && predictRed.equals(drawRed)) {
                    redMatches++;
                    break;
                }
            }
        }
        
        // 比较蓝球
        boolean blueMatch = record.getBlueBall() != null && 
                           record.getBlueBall().equals(draws.getBlueBall());
        
        // 根据中奖规则判断奖项
        if (redMatches == 6 && blueMatch) {
            return "一等奖";
        } else if (redMatches == 6) {
            return "二等奖";
        } else if (redMatches == 5 && blueMatch) {
            return "三等奖";
        } else if ((redMatches == 5) || (redMatches == 4 && blueMatch)) {
            return "四等奖";
        } else if ((redMatches == 4) || (redMatches == 3 && blueMatch)) {
            return "五等奖";
        } else if (blueMatch && (redMatches == 0 || redMatches == 1 || redMatches == 2)) {
            return "六等奖";
        } else {
            return "未中奖";
        }
    }
    
    /**
     * 计算奖金
     */
    private long calculateBonus(String result) {
        switch (result) {
            case "一等奖":
                return 5000000L; // 500万
            case "二等奖":
                return 1000000L; // 100万
            case "三等奖":
                return 3000L;    // 3000元
            case "四等奖":
                return 200L;     // 200元
            case "五等奖":
                return 10L;      // 10元
            case "六等奖":
                return 5L;       // 5元
            default:
                return 0L;
        }
    }
} 